<template>
  <div>
    <!-- 头部导航 -->
    <van-nav-bar title="登录" class="navbar" />

    <!-- 手机号/验证码表单 -->
    <van-form @submit="onSubmit" class="from" ref="form">
      <!-- 表单中的输入框组件。 -->
      <!-- 1.input没有name不能提交数据 -->
      <!-- 2.from表单中 button可以触发submit事件 -->
      <!-- 3.name属性标识input框 -->
      <!-- rules: 表单校验规则，数组，数组里每一个对象对应一个表单规则 -->
      <van-field
        v-model="mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="mobileRules"
      >
        <template #label>
          <span class="toutiao toutiao-shouji"></span>
        </template>
      </van-field>
      <van-field
        v-model="code"
        name="code"
        placeholder="请输入验证码"
        :rules="codeRules"
      >
        <template #label>
          <span class="toutiao toutiao-yanzhengma"></span>
        </template>
        <template #button>
          <van-button
            size="small"
            type="default"
            round
            class="cade-btn"
            native-type="button"
            @click="getCode"
            v-if="isShowCodeFn"
            >获取验证码</van-button
          >
          <van-count-down
            :time="3 * 1000"
            v-else
            format="ss秒"
            @finish="isShowCodeFn = true"
          />
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI, getCodeAPI } from '@/api'
import { mapMutations } from 'vuex'
export default {
  name: 'LogIn',
  data() {
    const mobileRules = [
      { required: true, message: '请输入手机号' },
      {
        pattern: /^1[3|5|7|8]\d{9}$/,
        message: '你输入的手机号非法'
      }
    ]
    const codeRules = [
      { required: true, message: '请输入验证码' },
      { pattern: /^\d{6}$/, message: '验证码格式错误' }
    ]
    return {
      mobile: '',
      code: '',
      mobileRules,
      codeRules,
      isShowCodeFn: true
    }
  },
  methods: {
    ...mapMutations(['SET_TOKEN']),
    async onSubmit() {
      const { code, mobile } = this
      //   console.log(code,mobile);
      //   const res = await loginAPI(mobile, code);
      //   console.log(res);
      this.$toast.loading({
        message: '加载中...', // loading提示
        forbidClick: true // forbid:禁止点击
      })
      try {
        const { data } = await loginAPI(mobile, code)
        this.SET_TOKEN(data.data)
        this.$router.push('/profile')
        this.$toast.success('登录成功')
      } catch (error) {
        // console.log(error);
        // this.$toast.fail('登录失败')

        // 区分是js导致的错误还是axios导致的错误
        // axios封装对象的错误
        // - 对象.response.data储存着后端返回的数据
        // - 对象.response.status 后端返回的状态码
        // if(error.response && error.reaponse.status === 400) {
        if (error.response?.status === 400) {
          // 可选链操作符
          this.$toast.fail(error.response.data.message)
        } else {
          throw error
        }
      }
    },
    async getCode() {
      // 确保输入了有效的手机号
      // 1.给form 表单绑定ref
      // 传入的是name属性
      await this.$refs.form.validate('mobile')

      // 2.显示倒计时
      this.isShowCodeFn = false

      // 3.提示loading
      this.$toast.loading({
        message: '发送验证码中...',
        forbidClick: true
      })

      // 4.发送验证码
      try {
        await getCodeAPI(this.mobile)
        this.$toast.success('发送验证码成功！')
      } catch (error) {
        if (error.response?.status === 429) {
          // 频繁发送验证码
          this.$toast.fail(error.response.data.message)
        } else {
          throw error
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
//scoped作业：样式只能对当前组件生效
//vue-cli提供的语法，样式穿透： ：deep()
// /deep/ 旧语法
.navbar {
  background-color: #3296fa;
  :deep(.van-nav-bar__title) {
    color: #fff;
  }
}
:deep(.from) {
  .toutiao {
    font-size: 40px;
  }
  .van-field__label {
    flex: 1;
  }
  .van-field__value {
    flex: 20;
  }
}
.cade-btn {
  background-color: #eeeeee;
  color: #9a8b7e;
  height: 0.64rem;
}
</style>
